package com.commonmodule.commonmodule.util;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.data.redis.core.Cursor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zxb
 * @version 1.0
 * @date 2024-11-05 11:50
 */
@Component
public class RedisUtil {

    @Resource
    public StringRedisTemplate stringRedisTemplate;


    /**
     * 添加缓存
     * @param key
     * @param value
     * @param timeout 过期时间
     * @param unit 时间单位
     */
    public void save(String key, String value, long timeout, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key,value,timeout,unit);
    }

    public void save(String key, String value){
        stringRedisTemplate.opsForValue().set(key,value);
    }


    /**
     * 根据键获取值
     * @param key  键
     * @return 值
     */
    public String select(String key){
        return stringRedisTemplate.opsForValue().get(key);
    }


    /**
     * 校验是否存在该键
     * @param key  键
     * @return
     */
    public boolean verify(String key){
        return stringRedisTemplate.hasKey(key);
    }


    /**
     * 根据key删除缓存
     * @param key
     */
    public void del(String key){
        stringRedisTemplate.delete(key);
    }


    /**
     * 删除以该字符串开头的所有key
     * @param s
     */
    public void deleteKeys(String s) {
        ArrayList<String> keys = new ArrayList<>();
        // 使用 SCAN 命令来查找匹配的键
        Cursor<byte[]> cursor = stringRedisTemplate.execute(
                (RedisCallback<Cursor<byte[]>>) connection -> connection.scan(ScanOptions.scanOptions().match(s + "*").count(100).build())
        );
        // 遍历结果
        while (cursor.hasNext()) {
            keys.add(new String(cursor.next()));
        }
        stringRedisTemplate.delete(keys);
    }




}
